from django.contrib.auth.hashers import check_password
from rest_framework import serializers

from ares.models import Area
from ares.serializer import AreasSerializer
from user.models import User, Address
from utils.errors import ParamsException


class UserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(required=True)

    class Meta:
        model = User
        fields = ['username']


class UserRegisterSerializer(serializers.Serializer):
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True)
    password2 = serializers.CharField(required=True)
    mobile = serializers.CharField(required=True)
    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            res = {'count': 2333, 'msg': '密码不一致'}
            raise ParamsException(res)
        if User.objects.filter(username=attrs['username']).exists():

            res = {'count': 2334, 'msg': '用户已被注册'}
            raise ParamsException(res)
        if User.objects.filter(mobile=attrs['mobile']).exists():
            res = {'count': 2335, 'msg': '电话已被注册'}
            raise ParamsException(res)

        return attrs

    # def create(self, validated_data):

class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True)
    # mobile = serializers.CharField(required=True)


    def validate(self, attrs):

        user = User.objects.filter(username=attrs['username']).first()
        if not user:
            res = {'code': 2333,
                   'msg': '请求成功,但是没有此用户',
                   }
            raise ParamsException(res)
        if not check_password(attrs['password'], user.password):

            res = {'code': 2333,
                   'msg': '请求成功,但是用户密码不匹配',
                   }
            raise ParamsException(res)

        return attrs



class UserAddressSerializer(serializers.ModelSerializer):
    province = AreasSerializer()
    city = AreasSerializer()
    district = AreasSerializer()

    class Meta:
        model = Address
        fields = '__all__'


